﻿using Microsoft.IdentityModel.Tokens;
using MyCommon.DB;
using MyModels.ViewModels;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace MyExtension.Authorizations
{
    public class JwtToken
    {
        /// <summary>
        /// 生成 Jwt Token
        /// </summary>
        /// <param name="claims"></param>
        /// <param name="permissionRequirement"></param>
        /// <returns></returns>
        public static TokenInfoViewModel BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement)
        {
            var now = DateTime.Now;
            var jwt = new JwtSecurityToken(
                issuer: permissionRequirement.Issure,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(permissionRequirement.Expiration),
                signingCredentials: permissionRequirement.SigningCredentials
                );

            var token = new JwtSecurityTokenHandler().WriteToken(jwt);
            var response = new TokenInfoViewModel
            {
                success = true,
                token = token,
                expires_in = permissionRequirement.Expiration.TotalSeconds,
                token_type = "Bearer"
            };
            return response;
        }

        /// <summary>
        /// 解析Token
        /// </summary>
        /// <param name="jwtTokenStr"></param>
        /// <returns></returns>
        public static TokenModelJwt SerializeToken(string jwtTokenStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var tokenModel = new TokenModelJwt();

            if (!string.IsNullOrEmpty(jwtTokenStr) && jwtHandler.CanReadToken(jwtTokenStr)) { 
                JwtSecurityToken jwtToken  = jwtHandler.ReadJwtToken(jwtTokenStr);
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out var role);
                tokenModel = new TokenModelJwt
                {
                    Uid = Convert.ToInt64(jwtToken.Id),
                    Role = role != null ? role.ToString() : ""
                };
            }
            return tokenModel;
        }

        /// <summary>
        /// 自定义验证token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static bool customSafeVerify(string token)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var symmetricKeyAsBase64 = AppSecretConfig.Audience_Secret_String;
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            try
            {
                var jwt = jwtHandler.ReadJwtToken(token);
                return jwt.RawSignature == Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(jwt.RawHeader + "." + jwt.RawPayload, signingCredentials);
            }
            catch (Exception ex)
            {
                return false;
            }
           
        }
    }

    public class TokenModelJwt
    {
        public long Uid { get; set; }
        public string Role { get; set; }
        public string Work { get; set; }
    }
}
